<template>
  <div class="product-detail-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: 'CategoryList' }">商品分类</el-breadcrumb-item>
        <el-breadcrumb-item>{{ product.category?.name }}</el-breadcrumb-item>
        <el-breadcrumb-item>{{ product.productName }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 商品详情主体 -->
    <div class="product-main">
      <!-- 商品图片展示 -->
      <div class="product-gallery">
        <div class="main-image">
          <el-image
              :src="product.avatar"
              fit="contain"
              :preview-src-list="[product.avatar]"
          />
        </div>
      </div>

      <!-- 商品信息 -->
      <div class="product-info">
        <h1 class="product-title">{{ product.productName }}</h1>

        <div class="product-meta">
          <div class="meta-item">
            <span class="meta-label">品牌：</span>
            <span class="meta-value">{{ product.brand?.name || '暂无品牌信息' }}</span>
          </div>
          <div class="meta-item">
            <span class="meta-label">分类：</span>
            <span class="meta-value">{{ product.category?.name || '暂无分类信息' }}</span>
          </div>
        </div>

        <div class="price-section">
          <span class="price-label">价格：</span>
          <span class="price">¥{{ product.price }}</span>
        </div>

        <!-- 购买操作区域 -->
        <div class="action-section">
          <div class="quantity-selector">
            <span class="label">数量：</span>
            <el-input-number
                v-model="quantity"
                :min="1"
                :max="99"
                size="large"
            />
          </div>

          <div class="action-buttons">
            <el-button
                type="danger"
                size="large"
                @click="addToCart"
            >
              加入购物车
            </el-button>
            <el-button
                type="warning"
                size="large"
                @click="handleBuyNow"
            >
              立即购买
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 商品详情描述 -->
    <div class="product-description">
      <h2 class="section-title">商品详情</h2>
      <div class="description-content" v-html="product.description"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const route = useRoute()
const product = ref({
  productName: '',
  price: 0,
  avatar: '',
  description: '',
  brand: {},
  category: {}
})
const quantity = ref(1)

// 获取商品详情
const fetchProductDetail = async () => {
  try {
    const productId = route.params.productId
    const response = await axios.get(`/api/brand/brand/findProductById?productId=${productId}`)

    if (response.data?.code === 200) {
      product.value = response.data.data
    } else {
      ElMessage.error(response.data?.message || '获取商品详情失败')
    }
  } catch (error) {
    ElMessage.error('获取商品详情失败: ' + error.message)
    console.error('获取商品详情失败:', error)
  }
}

// 加入购物车
const addToCart = () => {
  ElMessage.success(`已添加 ${quantity.value} 件商品到购物车`)
  // 这里可以调用购物车API
  console.log('加入购物车:', product.value.id, quantity.value)
}

// 立即购

const payLoading = ref(false);
const payDialogVisible = ref(false);
const payForm = ref('');

const handleBuyNow = async () => {
  const userId = 2 // TODO: 替换为实际登录用户ID
  const productId = product.value.productId || product.value.id
  const num = quantity.value

  try {
    payLoading.value = true;

    // 1. 创建订单
    const orderRes = await axios.post('/api/orders/orders/addOrder', {
      userId: userId,
      items: [
        {
          productId: productId,
          productNum: num
        }
      ]
    });

    if (orderRes.data.code === 200) {
      const { orderNo, amount } = orderRes.data.data;

      // 2. 调用支付接口获取支付表单HTML
      const payRes = await axios.post('/api/orders/payment/create', {
        orderNo: orderNo,
        amount: amount,
        subject: product.value.productName
      }, {
        responseType: 'text' // 重要：接收原始HTML响应
      });

      // 3. 创建新窗口显示支付页面
      const payWindow = window.open('', '_blank');
      payWindow.document.write(payRes.data);
      payWindow.document.close();

    } else {
      ElMessage.error(orderRes.data.message || '下单失败');
    }
  } catch (e) {
    ElMessage.error('下单失败: ' + e.message);
    console.error('下单失败:', e);
  } finally {
    payLoading.value = false;
  }
}
onMounted(() => {
  fetchProductDetail()
})
</script>

<style scoped>
.product-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
}

.breadcrumb {
  padding: 10px 0;
  margin-bottom: 20px;
}

.product-main {
  display: flex;
  margin-bottom: 40px;
}

.product-gallery {
  width: 450px;
  margin-right: 50px;
}

.main-image {
  width: 100%;
  height: 450px;
  border: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.main-image .el-image {
  width: 100%;
  height: 100%;
}

.product-info {
  flex: 1;
}

.product-title {
  font-size: 24px;
  margin: 0 0 20px;
  color: #333;
}

.product-meta {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.meta-item {
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.meta-label {
  color: #999;
}

.price-section {
  margin-bottom: 30px;
}

.price-label {
  font-size: 14px;
  color: #999;
}

.price {
  font-size: 24px;
  color: #e1251b;
  font-weight: bold;
}

.action-section {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.quantity-selector {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.quantity-selector .label {
  margin-right: 15px;
  font-size: 14px;
  color: #666;
}

.action-buttons {
  display: flex;
  gap: 15px;
}

.action-buttons .el-button {
  flex: 1;
}

.product-description {
  padding: 30px 0;
  border-top: 1px solid #eee;
}

.section-title {
  font-size: 18px;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.description-content {
  line-height: 1.6;
  color: #666;
}

.description-content img {
  max-width: 100%;
  height: auto;
}
</style>
